<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\model;
use think\Model;
use think\facade\Db;
class FeedbackCatModel extends Model{
    const modelTempPath = 'data/feedbackTemp/'; //模型表单模板路径    
    protected $name = 'feedback_cat';
    protected $pk = 'catid';
    /**
     * 更新模型模板文件
     * @param type $modelId 模型id
     * @return boolean
     */
    public function updateModelTemp($catid){
        $model=$this->find($catid);
        //将model里的is_enter is_contribute must_enter is_list is_search is_sort 依次拿出来和table_field对比，如果不存在就删除（防止因删除字段和修改字段名而造成model里的这些字段不更新导致的错误）
        $field=Db::name("feedback_field")->field("field")->order("sort asc,field_id asc")->select();   
        $new=[];
        $new["catid"]=$catid;
        foreach($field as $v){
            //录入项
            if(strstr($model['is_enter'], ",".$v["field"].",")){
                $new["is_enter"].=",".$v["field"];
            }            
            //必填项
            if(strstr($model['must_enter'], ",".$v["field"].",")){
                $new["must_enter"].=",".$v["field"];
            }           
        }
        $new["is_enter"]=isset($new["is_enter"])?$new["is_enter"].",":"";
        $new["must_enter"]=isset($new["must_enter"])?$new["must_enter"].",":"";      
        $this->update($new);   
        //
        $formtemp=  explode("\r\n",$model['formtemp']);
        $modelTemp="";
        foreach($formtemp as $key=>$v){
            $f=explode("<!--field-->",$v);
            if(isset($f[1])){
                if(!strstr($new["is_enter"], ",".$f[1].",")){
                    continue;;
                }
                $field=Db::name("feedback_field")->where([["field","=",$f[1]]])->find();
                if($field){
                    $htmlcode=$field["htmlcode"];
                    $htmlcode=  str_replace("{modelFieldTemp_name}", $f[0],$htmlcode);//名称替换
                    $modelTemp=$modelTemp."\r\n".$htmlcode;                
                }
            }
        }
        //
        $modelTemp=htmlspecialchars_decode($modelTemp);
        file_put_contents(base_path().self::modelTempPath.$catid.".html",$modelTemp);
        return true;
    }
    //自动完成-get_formtemp
    public function get_formtemp($data) {
        $field_name=$data['field_name'];
        $field=$data['field'];
        $str="";
        foreach($field as $key=>$v){
            $str.=$field_name[$key]."<!--field-->".$field[$key]."\r\n";
        }        
        return trim($str);
    }     
    //把数组转换为字符串便于存到数据里
    public function arr2string($arr){
        $str=  $arr?implode(",", $arr):"";
        if($str){
            $str=",".$str.",";
        }
        return $str;
    }       
}
